//
//  CustomWebviewVC.m
//  ShandsMod
//
//  Created by zh s on 2023/3/20.
//  Copyright © 2023 zh_s. All rights reserved.
//

#import "CustomWebviewVC.h"
#import <WebKit/WebKit.h>


@interface CustomWebviewVC ()<WKUIDelegate,WKNavigationDelegate,UIGestureRecognizerDelegate> {
    UILongPressGestureRecognizer *_longPress;
    UIView *statusBarView;
}
//设置加载进度条
@property (nonatomic,strong) UIProgressView *progressView;
@property (nonatomic, strong) WKWebView *baseWebView;

@end

@implementation CustomWebviewVC

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //上面有灰度，想要白色，可以加白色view  但是不是
    statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, STATUS_BAR_HEIGHT)];
    statusBarView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:statusBarView];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [ToolsClass clearCacheAtPath:[ToolsClass getCachesPath] withBlock:^(BOOL finish) {
        if (finish) {
        }
    }];

    [self.view addSubview:self.baseWebView];
    self.navTitle = @"加载中...";
    //直接访问此url会访问失败 或者出现白屏情况
    //原因 掺杂中文uincode 或者一些 特殊字符 处理方式如下：
    //使用stringByAddingPercentEncodingWithAllowedCharacters处理
    NSString *headImgURL = [self.urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet  URLQueryAllowedCharacterSet]];
    [self.baseWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:headImgURL]]];
    if (_isShowNav) {
        self.leftTitle = @"close.png";
        [self.nav.leftView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(WIDTH_CONSTARIN(20));
            make.centerY.mas_equalTo(self.nav.titleLabel.mas_centerY);
            make.size.mas_equalTo(CGSizeMake(25, 25));
            
        }];
    }
    
    [self.baseWebView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];

    [self.baseWebView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    

    
    JTDLog(@"0----%@",self.urlStr);
    self.fd_interactivePopDisabled = YES;
    
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, NAV_HEIGHT - 1, SCREEN_WIDTH, 4)];
    self.progressView.backgroundColor = UIColor.whiteColor;
    self.progressView.progressTintColor = Nav1890FFColor;
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的0.5f.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.5f);
    [self.view addSubview:self.progressView];
}

#pragma mark ================ WKNavigationDelegate ================
//这个是网页加载完成，导航的变化
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  //  [XLPaymentLoadingHUD hideIn:self.view];
    JTDLog(@"加载完成了%@",webView.URL.absoluteString);
    if (!IsStrEmpty(self.navTitleStr)) {
        self.navTitle = self.navTitleStr;
    }else {
        self.navTitle = self.baseWebView.title;
        
    }
    
    self.progressView.progress = 1;
    [self performSelector:@selector(hiddenprogressView) withObject:nil afterDelay:0.5];
}

- (void)hiddenprogressView{
    self.progressView.hidden = YES;
}

//开始加载
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    //开始加载的时候，让加载进度条显示
    JTDLog(@"开加载了");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
  //  [XLPaymentLoadingHUD showIn:self.view];
}

//内容返回时调用
-(void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    JTDLog(@"返回内容了");
}

//服务器请求跳转的时候调用
-(void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}

// 通常用于处理跨域的链接能否导航
// 在发送请求之前，决定是否允许或取消导航。
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    JTDLog(@"加载的url=%@",webView.URL.absoluteString);
    //    https://blog.csdn.net/qq_28160831/article/details/88908031 图片链接 无法跳转
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

// 内容加载失败时候调用
-(void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    self.navTitle = @"加载失败";
    self.progressView.hidden = YES;

    JTDLog(@"页面加载超时");
  //  [XLPaymentLoadingHUD hideIn:self.view];
    //加载失败 清除缓存
    [ToolsClass clearCacheAtPath:[ToolsClass getCachesPath] withBlock:^(BOOL finish) {
        if (finish) {
        }
    }];
    
    
}

//跳转失败的时候调用
-(void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
  //  [XLPaymentLoadingHUD hideIn:self.view];
}

//进度条
-(void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
    //    // 在该函数里执行[webView reload](这个时候 webView.URL 取值尚不为 nil）解决白屏问题。
    //    [webView reload];
}

// 如果是OC
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        NSURLCredential * card = [[NSURLCredential alloc] initWithTrust:challenge.protectionSpace.serverTrust];
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
    }
}

//- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
////    webView
//}

#pragma mark ================ WKUIDelegate ================

-(void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    decisionHandler(WKNavigationResponsePolicyAllow);
    
}

// 获取js 里面的提示
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

// js 信息的交流
-(void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
}

// 交互。可输入的文本。
-(void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];
    
    [self presentViewController:alert animated:YES completion:NULL];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.baseWebView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 0.5f);
            } completion:^(BOOL finished) {
                //  weakSelf.progressView.hidden = YES;
                
            }];
        }
    }else if ([keyPath isEqualToString:@"title"]){
        if (![self.navTitle isEqualToString:self.baseWebView.title]) {
            self.navTitle = self.baseWebView.title;
        }
    }
    else{
        //        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

- (void)leftViewClick {
    [ToolsClass clearCacheAtPath:[ToolsClass getCachesPath] withBlock:^(BOOL finish) {
        if (finish) {
        }
    }];
    if (self.isPresendeView) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else {
        [self.navigationController popViewControllerAnimated:YES];
    }
    
    
}
#pragma mark -- 懒加载
- (WKWebView *)baseWebView {
    if (!_baseWebView) {
        if (_isShowNav) {
            _baseWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NAV_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - NAV_HEIGHT)];
        }else {
            _baseWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - STATUS_BAR_HEIGHT)];
        }
        _baseWebView.backgroundColor = BASE_BACKCOLOR;
        _baseWebView.UIDelegate = self;
        _baseWebView.navigationDelegate = self;
        //隐藏滚动条
        _baseWebView.scrollView.showsVerticalScrollIndicator = NO;
        //添加此属性可触发侧滑返回上一网页与下一网页操作
        _baseWebView.allowsBackForwardNavigationGestures = YES;
        
        //适应你设定的尺寸
        [_baseWebView sizeToFit];
        
        
        
    }
    return _baseWebView;
}



- (void)dealloc {
    [self.baseWebView removeObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [self.baseWebView removeObserver:self forKeyPath:@"title"];
    
}


@end
